package com.lwlk.demo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lwlk.demo.dao.UserDao;
import com.lwlk.demo.dao.UserRepository;
import com.lwlk.demo.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("index")
public class IndexController {

    private final UserRepository userRepository;

    private final UserDao userDao;

    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    public IndexController(UserRepository userRepository, UserDao userDao) {

        this.userRepository = userRepository;

        this.userDao = userDao;
    }

    @GetMapping("allUser")
    @ResponseBody
    public Object getAllUser() throws JsonProcessingException {

        List<UserEntity> userList = userRepository.findAll();

        return "allUser = " + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(userList);
    }

    @GetMapping("allHqlUser/{name}")
    @ResponseBody
    public Object getAllUserByHql(@PathVariable String name) throws JsonProcessingException {

        return "allUser = " + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(userDao.findByHql(name));
    }

    @GetMapping("allCrUser")
    @ResponseBody
    public Object getAllUserByCr() throws JsonProcessingException {

        return "allUser = " + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(userDao.findByCr());
    }

    @GetMapping("addUser/{name}/{password}")
    @ResponseBody
    public Object addUser(@PathVariable String name, @PathVariable String password) throws JsonProcessingException {

        UserEntity user = new UserEntity(null, name, password);

        userRepository.save(user);

        return "addUser = " + objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
    }
}
